package net.portly.cst.output;

import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import net.portly.cst.StructuralAssetInstance;
import net.portly.cst.flex.FlexFamily;
import net.portly.cst.flex.FlexItemType;

public class ToJSONOutputFormat extends BaseOutputFormat {
	private FlexItemType[] itemTypes = new FlexItemType[] { FlexItemType.ATTRIBUTE, FlexItemType.PARENTDEF, FlexItemType.FLEXDEF, FlexItemType.PARENT,
			FlexItemType.FLEXASSET, FlexItemType.FILTER };

	@SuppressWarnings("unchecked")
	@Override
	public String getOutput() {

		JSONArray families = new JSONArray();
		
		for (FlexFamily flexFamily : assetModel.getFlexFamilies()) {
			JSONObject object = new JSONObject();
			
			object.put("familyname", flexFamily.getFamilyName());
			
//			System.out.println(flexFamily.getFamilyName());
			
			for (FlexItemType itemType : itemTypes) {
				jsonicateFlexItemType(flexFamily.getStructuralAssetInstancesForType(itemType), object, itemType);
			}

			families.add(object);
//			System.out.println("-" + families.toJSONString());
		}

		JSONObject ffObject = new JSONObject();
		ffObject.put("flexfamilies", families);
		
		return ffObject.toJSONString();
	}

	private void jsonicateFlexItemType(List<StructuralAssetInstance> structuralAssetInstances, JSONObject jsonObject, FlexItemType itemType) {
		if (structuralAssetInstances != null && structuralAssetInstances.size() > 0) {
			JSONArray itemArray = new JSONArray();

			for (StructuralAssetInstance saInstance : structuralAssetInstances) {
				JSONObject itemObj = new JSONObject();
				itemObj.put("name", saInstance.getName());
				itemObj.put("id", saInstance.getId());
				itemObj.put("fw_uid", saInstance.getFw_uid());
				itemObj.put("description", saInstance.getDescription());
				itemObj.put("createdby", saInstance.getCreatedby());
				itemObj.put("createddate", saInstance.getCreateddate());
				itemObj.put("type", saInstance.getType());
				itemObj.put("updatedby", saInstance.getUpdatedby());
				itemObj.put("updateddate", saInstance.getUpdateddate());
				itemArray.add(itemObj);
			}

			jsonObject.put(itemType.getType(), itemArray);
		}
	}

}
